<template>  
  <div class="fulltable">  
    <div class="full">  
      <div class="add">  
        <button class="button" @click="showAddModal = true">➕新增</button>  
      </div>  

      <div class="search-box">  
        <el-input  
          v-model="searchQuery"  
          placeholder="搜索标题"  
          clearable  
          style="width:200px;margin-right: 10px;"
        >
        </el-input>  

        <el-select v-model="selectedStatus" placeholder="筛选状态" clearable style="width:200px;margin-right: 10px;">  
          <el-option  
            v-for="status in selectstateOptions"  
            :key="status.value"  
            :label="status.label"  
            :value="status.value"  
          ></el-option>  
        </el-select>  

        <el-select v-model="selectedType" placeholder="筛选类型" clearable>  
          <el-option  
            v-for="type in typeOptions"  
            :key="type.value"  
            :label="type.label"  
            :value="type.value"  
          ></el-option>  
        </el-select>  
      </div>  

      <el-table  
        :data="filteredNoticeData.slice(  
          (currentPage - 1) * pageSize,  
          currentPage * pageSize  
        )"  
        :height="tableHeight"  
        border  
        style="width: 100%"  
      >  
        <el-table-column prop="type" label="类型" width="100"></el-table-column>  
        <el-table-column prop="state" label="状态" width="100"></el-table-column>  
        <el-table-column prop="title" label="标题" width="200"></el-table-column>  
        <el-table-column prop="releasetime" label="发布时间" width="180"></el-table-column>  
        <el-table-column prop="releaseperson" label="发布人" width="140"></el-table-column>  
        <el-table-column prop="dept" label="部门" width="140"></el-table-column>  
        <el-table-column label="操作">  
          <template slot-scope="scope">  
            <el-button type="primary" size="small" @click="viewItem(scope.row)">详情</el-button>  
            <el-button 
              v-if="canEditItem(scope.row)" 
              type="warning" 
              size="small" 
              @click="editItem(scope.row)">编辑</el-button>  
            <el-button 
              v-if="canDeleteItem(scope.row)" 
              type="danger" 
              size="small" 
              @click="deleteItem(scope.row)">删除</el-button>  
          </template>  
        </el-table-column>  
      </el-table>  

      <div class="paging">  
        <el-pagination  
          @size-change="handleSizeChange"  
          @current-change="handleCurrentChange"  
          :current-page="currentPage"  
          :page-sizes="[5, 10, 20, 40, 60]"  
          :page-size="pageSize"  
          :pager-count="4"  
          layout="total, sizes, prev, pager, next, jumper"  
          :total="filteredNoticeData.length"  
        ></el-pagination>  
      </div>  
    </div>  

    <el-dialog title="新增通知公告" :visible.sync="showAddModal" width="30%">  
      <el-form :model="newNotice" label-width="80px" ref="newNoticeForm">  
        <el-form-item label="类型" prop="type" :rules="[{ required: true, message: '类型不能为空' }]">  
          <el-select v-model="newNotice.type" placeholder="请选择类型">  
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>  
          </el-select>  
        </el-form-item>  
        <el-form-item label="状态" prop="state" :rules="[{ required: true, message: '状态不能为空' }]">  
          <el-select v-model="newNotice.state" placeholder="请选择状态">  
            <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>  
          </el-select>  
        </el-form-item>  
        <el-form-item label="标题" prop="title" :rules="[{ required: true, message: '标题不能为空' }]">  
          <el-input v-model="newNotice.title"></el-input>  
        </el-form-item>  
        <el-form-item label="描述" prop="desc" :rules="[{ required: true, message: '详细描述不能为空' }]">  
          <el-input v-model="newNotice.desc"></el-input>  
        </el-form-item>  

        <el-form-item label="发布时间" prop="releasetime" :rules="[{ required: true, message: '发布时间不能为空' }]">  
          <el-date-picker v-model="newNotice.releasetime" type="datetime" placeholder="选择发布时间"></el-date-picker>  
        </el-form-item>  
        <!-- <el-form-item label="发起人" prop="promoter">  
          <el-select v-model="newNotice.promoter" filterable placeholder="请选择发起人" style="width:400px">  
            <el-option v-for="item in userList" :key="item.id" :label="item.realname" :value="item.id"></el-option>  
          </el-select>  
        </el-form-item>   -->
        <el-form-item label="部门" prop="deptname">  
          <el-select v-model="newNotice.deptname" filterable placeholder="请选择部门,不选则默认发所有人" style="width:400px">  
            <el-option v-for="item in deptList" :key="item.id" :label="item.deptname" :value="item.id"></el-option>  
          </el-select>  
        </el-form-item>  
        <el-form-item label="接收人" prop="receiverList">  
          <el-select v-model="receiverList" multiple placeholder="请选择接收人，不填则视为发部门下所有人" style="width:400px">  
            <el-option v-for="item in userByDept" :key="item.id" :label="item.realname" :value="item.id"></el-option>  
          </el-select>  
        </el-form-item>  
        <el-form-item label="审核人" prop="reviewer" v-if="!isSuperman">  
            <el-input  v-model="fatherName" style="width:400px" disabled></el-input>  
        </el-form-item>  
      </el-form>  
      <span slot="footer" class="dialog-footer">  
        <el-button @click="closeAddModal">取 消</el-button>  
        <el-button type="primary" @click="saveNewNotice">确 定</el-button>  
      </span>  
    </el-dialog>  

    <el-dialog title="编辑通知公告" :visible.sync="showEditModal" width="30%">  
      <el-form :model="newNotice" label-width="80px" ref="editNoticeForm">  
        <el-form-item label="类型" prop="type" :rules="[{ required: true, message: '类型不能为空' }]">  
          <el-select v-model="newNotice.type" placeholder="请选择类型">  
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>  
          </el-select>  
        </el-form-item>  
        <el-form-item label="状态" prop="state" :rules="[{ required: true, message: '状态不能为空' }]">  
          <el-select v-model="newNotice.state" placeholder="请选择状态">  
            <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>  
          </el-select>  
        </el-form-item>  
        <el-form-item label="标题" prop="title" :rules="[{ required: true, message: '标题不能为空' }]">  
          <el-input v-model="newNotice.title"></el-input>  
        </el-form-item>  
        <el-form-item label="描述" prop="desc" :rules="[{ required: true, message: '详细描述不能为空' }]">  
          <el-input v-model="newNotice.desc"></el-input>  
        </el-form-item>  

        <el-form-item label="发布时间" prop="releasetime" :rules="[{ required: true, message: '发布时间不能为空' }]">  
          <el-date-picker v-model="newNotice.releasetime" type="datetime" placeholder="选择发布时间"></el-date-picker>  
        </el-form-item>  
        <!-- <el-form-item label="发起人" prop="promoter">  
          <el-select v-model="newNotice.promoter" filterable placeholder="请选择发起人" style="width:400px">  
            <el-option v-for="item in userList" :key="item.id" :label="item.realname" :value="item.id"></el-option>  
          </el-select>  
        </el-form-item>   -->
        <el-form-item label="部门" prop="deptname">  
          <el-select v-model="newNotice.deptname" filterable placeholder="请选择部门,不选则默认发所有人" style="width:250px">  
            <el-option v-for="item in deptList" :key="item.id" :label="item.deptname" :value="item.id"></el-option>  
          </el-select>  
          <span style="color: #409EFF; margin-left: 10px;">当前部门：{{baseDept||"全部门"}}</span>
        </el-form-item>  
        <el-form-item label="接收人" prop="receiverList">  
          <el-select v-model="receiverList" multiple placeholder="请选择接收人，不填则视为发部门下所有人" style="width:250px">  
            <el-option v-for="item in userByDept" :key="item.id" :label="item.realname" :value="item.id"></el-option>  
          </el-select>  
        </el-form-item>  
        <el-form-item label="当前接收" prop="receiverList">
          <el-input type="textarea" v-model="newNotice.recipient" disabled style="width: 400px;"></el-input>
        </el-form-item>
        <el-form-item label="审核人" prop="reviewer">  
            <el-input  v-model="fatherName" style="width:400px" disabled></el-input>  
        </el-form-item> 
      </el-form>  
      <span slot="footer" class="dialog-footer">  
        <el-button @click="closeEditModal">取 消</el-button>  
        <el-button type="primary" @click="updateNotice">确 定</el-button>  
      </span>  
    </el-dialog>  

    <el-dialog title="通知公告详情" :visible.sync="showDetailModal" width="50%">  
      <el-form :model="detailItem" label-width="80px">  
        <el-form-item label="类型">  
          <el-input v-model="detailItem.type" disabled></el-input>  
        </el-form-item>  
        <el-form-item label="状态">  
          <el-input v-model="detailItem.state" disabled></el-input>  
        </el-form-item>  
        <el-form-item label="标题">  
          <el-input v-model="detailItem.title" disabled></el-input>  
        </el-form-item>  
        <el-form-item label="描述">  
          <el-input type="textarea" v-model="detailItem.desc" disabled></el-input>  
        </el-form-item>  
        <el-form-item label="发布时间">  
          <el-input v-model="detailItem.releasetime" disabled></el-input>  
        </el-form-item>  
        <el-form-item label="发起人">  
          <el-input v-model="detailItem.releaseperson" disabled></el-input>  
        </el-form-item>  
        <el-form-item label="部门">  
          <el-input v-model="detailItem.dept" disabled></el-input>  
        </el-form-item>  
        <el-form-item label="接收人">  
          <el-input v-model="detailItem.recipient" disabled></el-input>  
        </el-form-item>  
        <el-form-item label="审核人">  
          <el-input v-model="detailItem.reviewer" disabled></el-input>  
        </el-form-item>
        <el-form-item label="审核状态">
          <el-input v-model="detailItem.examine" disabled></el-input>  
        </el-form-item>
        <el-form-item label="审核原因">
          <el-input v-model="detailItem.exReason" disabled></el-input>  
        </el-form-item>  
      </el-form>  
      <span slot="footer" class="dialog-footer">  
        <el-button @click="showDetailModal = false">取 消</el-button>  
      </span>  
    </el-dialog>  
  </div>  
</template>  

<script>  
import { getNoticeList, addNotice, deleteNoticeById, getNoticeDetailById ,updateNotice} from '@/api/notice';  
import { getUserList, getUserByDeptId ,getAdminList,getChargeList,getFather} from '@/api/user';  
import { getDeptList } from '@/api/dept';  
import {jwtDecode } from 'jwt-decode';
import {addLog} from '@/api/log';
export default {  
  data() {  
    return { 
      logItem:{
              mn:'',
              opn:'',
              res:''
      }, 
      noticeData: [],  
      currentPage: 1,  
      pageSize: 5,  
      tableHeight: 300,  
      maxTableHeight: 700,  
      minTableHeight: 300,  
      showAddModal: false,  
      showEditModal: false,  
      showDetailModal: false,  
      detailItem: {},  
      searchQuery: '',  
      selectedStatus: '', // 新增：筛选状态  
      selectedType: '',   // 新增：筛选类型  
      newNotice: {  
        type: '',  
        state: '',  
        title: '',  
        desc: '',  
        releasetime: '',  
        reviewer: null,
        deptname: '',  
        receiverList: []  
      },  
      currentUserId: this.getUserId(),
      receiverList: [],  
      typeOptions: [  
        { label: '公告', value: '公告' },  
        { label: '通知', value: '通知' },  
        { label: '更新', value: '更新' },  
      ],  
      stateOptions: [  
        { label: '一般', value: 3 },  
        { label: '重要', value: 2 },  
        { label: '紧急', value: 1 }  
      ],  
      selectstateOptions: [  
        { label: '一般', value: '一般' },  
        { label: '重要', value: '重要' },  
        { label: '紧急', value: '紧急' }  
      ],  
      userList: [],  
      deptList: [],  
      userByDept: [],  
      adminList: [],
      bascadminList: [],
      isSuperman: false, // Add a property to track if the user is SUPERMAN
      fatherName:'',
      fatherId:'',
      baseDept:'',
    }  
  },  
  computed: {  
    filteredNoticeData() {  
      return this.noticeData.filter(item => {  
        const matchesTitle = item.title.toLowerCase().includes(this.searchQuery.toLowerCase());  
        const matchesStatus = this.selectedStatus ? item.state === this.selectedStatus : true; // 状态筛选  
        const matchesType = this.selectedType ? item.type === this.selectedType : true; // 类型筛选  
        return matchesTitle && matchesStatus && matchesType;  
      });  
    }  
  },  
  created() {  
    getNoticeList().then(response => {  
      this.noticeData = response.data;  
      this.calculateTableHeight();  
      console.log(response.data);  
    }).catch(error => {  
      console.log(error);  
      this.tableHeight = this.minTableHeight;  
    });  
    getFather().then(response=>{
      this.fatherName = response.data.realname;
      this.fatherId = response.data.id;
    })
    this.newNotice.reviewer = this.fatherId;
    this.getUsers();  
    this.getDepts();  
    this.getAdmins();  
    this.isSuperman = this.checkUserRole(); // Set isSuperman based on user role
  },  
  watch: {  
    currentPage() {  
      this.calculateTableHeight();  
    },  
    pageSize() {  
      this.calculateTableHeight();  
    },  
    'newNotice.deptname'(newVal) {  
      if(newVal){
      this.getUserByDept(newVal);  
      this.handleChargeList(newVal);}
    } , 
    'showAddModal'(newVal){
      if(newVal){
        getFather().then(response=>{
          this.fatherName = response.data.realname;
          this.fatherId = response.data.id;
        })
        this.newNotice.reviewer = this.fatherId;
      }
    }
  },  
  methods: {  
    handleChargeList(deptId){
        // 过滤 chargeList，只包含符合条件的用户  
        this.adminList = this.bascadminList.filter(user =>   
            user.role === 1 || (user.role === 2 && user.deptId === deptId)  
        );  
      },
    handleSizeChange(val) {  
      this.pageSize = val;  
      this.currentPage = 1;  
      this.logItem.mn = "handleSizeChange";
      this.logItem.opn = "改变每页显示的通知数量-通知管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
    handleCurrentChange(val) {  
      this.currentPage = val;  
      this.logItem.mn = "handleCurrentChange";
      this.logItem.opn = "改变页码-通知管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
    calculateTableHeight() {  
      const currentPageData = this.noticeData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);  
      let height = (currentPageData.length + 1) * 60;  
      this.tableHeight = Math.max(this.minTableHeight, Math.min(height, this.maxTableHeight));  
    },  
    saveNewNotice() {  
      this.$refs.newNoticeForm.validate((valid) => {  
        if (valid) {  
          this.newNotice.receiverList = this.receiverList;  
          addNotice(this.newNotice)  
            .then(response => {  
              this.$message.success('新公告添加成功');  
              this.showAddModal = false;  
              this.logItem.mn = "saveNewNotice";
              this.logItem.opn = "新增公告";
              this.logItem.res = "true";
              addLog(this.logItem);
              window.location.reload();  
            })  
            .catch(error => {  
              this.$message.error('新公告添加失败');  
              this.logItem.mn = "saveNewNotice";
              this.logItem.opn = "新增公告";
              this.logItem.res = "false";
              addLog(this.logItem);
              console.error(error);  
            });  
        } else {  
          return false;  
        }  
      });  
    },  
    getUsers() {  
      getUserList().then((response) => {  
        console.log(response.data);  
        this.userList = response.data;  
      });  
    },  
    getDepts() {  
      getDeptList().then((response) => {  
        console.log(response.data);  
        this.deptList = response.data;  
      });  
    },  
    handleDeptChange(deptId) {  
      this.getUserByDept(deptId);  
    },  
    getUserByDept(deptId) {  
      getUserByDeptId(deptId).then((response) => {  
        this.userByDept = response.data;  
      });  
    },  
    closeAddModal() {  
      window.location.reload();  
      this.showAddModal = false;  
      this.newNotice = {  
        type: '',  
        state: '',  
        title: '',  
        desc: '',  
        releasetime: '',  
        reviewer: null,
        deptname: '',  
        receiverList: [],
        id:''  
      };  
    },  
    deleteItem(row) {  
      this.$confirm('确定要删除此通知公告吗?', '警告', {  
        confirmButtonText: '确定',  
        cancelButtonText: '取消',  
        type: 'warning'  
      }).then(() => {  
        deleteNoticeById(row.id).then(response => {  
          this.noticeData = this.noticeData.filter(item => item.id !== row.id);  
          this.$message.success('通知公告删除成功');  
          this.logItem.mn = "deleteItem";
          this.logItem.opn = "删除公告";
          this.logItem.res = "true";
          addLog(this.logItem);
          window.location.reload();  
        }).catch(error => {  
          console.error(error);  
          this.logItem.mn = "deleteItem";
          this.logItem.opn = "删除公告";
          this.logItem.res = "false";
          addLog(this.logItem);
          this.$message.error('通知公告删除失败');  
        });  
      }).catch(() => {  
        this.$message.info('已取消删除');  
      });  
    },  
    viewItem(row) {  
      getNoticeDetailById(row.id).then((response) => {  
        this.detailItem = response.data;  
        console.log(response.data);  
        this.logItem.mn = "viewItem";
        this.logItem.opn = "查看公告详情-通知管理";
        this.logItem.res = "true";
        addLog(this.logItem);
        this.showDetailModal = true;  
      }).catch(() => {  
        this.logItem.mn = "viewItem";
        this.logItem.opn = "查看公告详情-通知管理";
        this.logItem.res = "false";
        addLog(this.logItem);
        this.$message.info('查看公告消息失败');  
      });  
    },  
    checkUserRole() {
      const token = localStorage.getItem('token'); // 从本地存储获取 token
      if (token) {
        const decodedToken = jwtDecode(token); // 解码 token
        return decodedToken.role === 'SUPERMAN'; // 检查角色
      }
      return false; // 无 token 返回 false
    },
    getUserId(){
      const token = localStorage.getItem('token'); // 从本地存储获取 token
      if(token){
        const decodedToken = jwtDecode(token); // 解码 token
        return decodedToken.userId; // 返回 userId
      }
      return null; // 无 token 返回 null
    },
    canDeleteItem(row) {
        const isSuperman = this.checkUserRole();
        console.log("currentUserId",this.currentUserId);
        console.log("row.userId",row.userId);
        if(isSuperman){
          return true;
        }else{
           return this.currentUserId === row.userId && row.examine !== "1"; 
        }
        return false;
       // 只有SUPERMAN或发布人是自己的才能删除
    },
    getAdmins() {
      getChargeList().then(response =>{
      this.adminList = response.data
      this.bascadminList = response.data
    })
    },
    canEditItem(row) {
      const isSuperman = this.checkUserRole();
        console.log("currentUserId",this.currentUserId);
        console.log("row.userId",row.userId);
        if(isSuperman){
          return true;
        }else{
          console.log("row.examine",row.examine);
           return this.currentUserId === row.userId && row.examine !=="1"; 
        }
        return false;
    },
    editItem(row) {
      this.newNotice = { ...row }; // 将选中的通知数据赋值给表单
      this.baseDept = row.dept;
      this.showEditModal = true; // 显示编辑弹窗
    },
    updateNotice() {
      this.$refs.editNoticeForm.validate((valid) => {
        if (valid) {
        if(this.newNotice.state === "紧急"){
          this.newNotice.state = "1";
        }else if(this.newNotice.state === "重要"){
          this.newNotice.state = "2";
        }else if(this.newNotice.state === "一般"){
          this.newNotice.state = "3";
        }
        this.newNotice.receiverList = this.receiverList;
          updateNotice(this.newNotice)
            .then(response => {
              this.$message.success('通知公告编辑成功');
              this.showEditModal = false; // 关闭编辑弹窗
              this.logItem.mn = "updateNotice";
              this.logItem.opn = "编辑通知";
              this.logItem.res = "true";
              addLog(this.logItem);
              window.location.reload(); // 刷新通知列表
            })
            .catch(error => {
              this.$message.error('通知公告未修改');
              if(this.newNotice.state === "1"){
                this.newNotice.state = "紧急";
              }else if(this.newNotice.state === "2"){
                this.newNotice.state = "重要";
              }else if(this.newNotice.state === "3"){
                this.newNotice.state = "一般";
              }
              this.logItem.mn = "updateNotice";
              this.logItem.opn = "编辑通知";
              this.logItem.res = "false";
              addLog(this.logItem);
              console.error(error);
            });
        } else {
          return false; // 表单验证失败的处理
        }
      });
    },
    closeEditModal() {
      this.showEditModal = false; // 关闭编辑弹窗
      this.newNotice = { // 重置表单数据
        type: '',
        state: '',
        title: '',
        desc: '',
        releasetime: '',
        reviewer: null,
        deptname: '',
        receiverList: [],
        id: ''
      };
    },
  }  
}  
</script>  

<style lang="less" scoped>
.fulltable{
  margin-top: 20px;
  height: 700px;

}
.full{
  height: 800px;
  margin: 0;
  padding: 0;
  background: pink;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;
}
.add{
  padding: 10px;
}
/deep/.el-table .cell {  
  color: black;
}  

.button{
  background: #788fd3;
  color: white;
}
.paging{
  margin: 0;
  padding: 0;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;

  /deep/ .el-pagination {
    display: flex;  
    justify-content: flex-end;  
  }
}
</style>